package com.gk.javaservice.controller;

import com.alibaba.fastjson.JSONArray;
import com.gk.javaservice.common.ServerResponse;
import com.gk.javaservice.po.AdminMenu;
import com.gk.javaservice.po.AdminRoleMenu;
import com.gk.javaservice.po.AdminUsers;
import com.gk.javaservice.service.AdminRoleMenuService;
import com.gk.javaservice.service.AdminRoleUsersService;
import com.gk.javaservice.service.AdminUsersService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/admin/AdminUsers")
public class AdminUsersController {
    private Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private AdminUsersService adminUsersService;
    @Autowired
    private AdminRoleUsersService adminRoleUsersService;

    //添加
    @CrossOrigin
    @ResponseBody
    @RequestMapping("/add")
    public ServerResponse<?> add(@RequestBody AdminUsers t) {

        log.info(t);

        try {
            adminUsersService.add(t);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("账号已存在");
        }


        return ServerResponse.createBySuccess(t.getId());

    }

    //根据ID删除1个
    @CrossOrigin
    @ResponseBody
    @RequestMapping("/delete")
    public ServerResponse<?> delete(@RequestBody AdminUsers t) {

        log.info("id:" + t.getId());
        adminUsersService.delete(t.getId());
        adminRoleUsersService.delete(t.getId());
        return ServerResponse.createBySuccess(t.getId());

    }

    //修改 信息
    @CrossOrigin
    @ResponseBody
    @RequestMapping("/update")
    public ServerResponse<?> update(@RequestBody AdminUsers t) {

        log.info("id:" + t.getId());
        log.info("id:" + t.getName());
        adminUsersService.update(t);
        return ServerResponse.createBySuccess(adminUsersService.hasById(t.getId()));

    }

    //获取所有 信息
    @CrossOrigin
    @ResponseBody
    @RequestMapping("/hasAll")
    public ServerResponse<?> hasAll() {

        log.info("in to hasAll");
        return ServerResponse.createBySuccess(adminUsersService.hasAll());

    }

    @CrossOrigin
    @ResponseBody
    @RequestMapping("/queryTotal")
    public ServerResponse<?> queryTotal(HttpServletRequest request) {
        String searchMsg = request.getParameter("searchMsg");
        if (searchMsg != null) {
            searchMsg = searchMsg.trim();
        }
        return ServerResponse.createBySuccess(adminUsersService.queryTotal(searchMsg));

    }

    //分页获取
    @CrossOrigin
    @ResponseBody
    @RequestMapping("/hasAllToPage")
    public ServerResponse<?> hasAllToPage(HttpServletRequest request) {
        int page = 1;
        int limit = 20;
        try {
            page = Integer.parseInt(request.getParameter("page"));
        } catch (Exception e) {

        }

        try {
            limit = Integer.parseInt(request.getParameter("limit"));
        } catch (Exception e) {

        }

        String searchMsg = request.getParameter("searchMsg");
        if (searchMsg != null) {
            searchMsg = searchMsg.trim();
        }

//        log.info("searchMsg:" + searchMsg);
        if (searchMsg == null)
            searchMsg = "";
        int offset = (page - 1) * limit;
        int queryTotal = adminUsersService.queryTotal(searchMsg);
        int maxPage = (queryTotal / limit) + 1;
        List<AdminUsers> alist = adminUsersService.hasAllToPage(offset, limit, searchMsg);
        HashMap<String, Object> map = new HashMap<>();

        map.put("queryTotal", queryTotal);
        map.put("maxPage", maxPage);
        map.put("page", page);
        map.put("list", alist);
        return ServerResponse.createBySuccess(map);

    }


    //根据ID获取 信息
    //根据ID获取终端信息
    @CrossOrigin
    @ResponseBody
    @RequestMapping("/hasById")
    public ServerResponse<?> hasById(HttpServletRequest request) {
        String id = request.getParameter("id");
        log.info("id:" + id);
        return ServerResponse.createBySuccess(adminUsersService.hasById(id));

    }

    @CrossOrigin
    @ResponseBody
    @GetMapping("/login")
    public ServerResponse<?> login(HttpServletRequest request, HttpSession session) {
        log.info("in to login");
//        int isLogin=Integer.parseInt(request.getParameter("isLogin"));
        AdminUsers u = new AdminUsers();
        u.setName(request.getParameter("name"));
        log.info("in to login");
        log.info(request.getParameter("name") + request.getParameter("pwd"));
        UsernamePasswordToken token = new UsernamePasswordToken(request.getParameter("name"), request.getParameter("pwd"));
        //UsernamePasswordToken token=new UsernamePasswordToken("root", MD5Encryption.encryption("123456",1,null,null));

        //UsernamePasswo//每天rdToken token=new UsernamePasswordToken("root", "123456");
        String token2 = UUID.randomUUID().toString(); // 生成唯一的token
        try {
            SecurityUtils.getSubject().login(token);
//            session.setAttribute("loginUser", SecurityUtils.getSubject().getSession().getAttribute("loginUser"));
            u = (AdminUsers) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
            u.setRemember_token(token2);

            session.setAttribute(token2, SecurityUtils.getSubject().getSession().getAttribute("loginUser"));

        } catch (AuthenticationException e) {
            e.printStackTrace();
            SecurityUtils.getSubject().logout();
            try {
                session.removeAttribute("loginUser");
            } catch (Exception ex) {

            }
            return ServerResponse.createByErrorMessage("登陆失败！");
        }

        u.setPassword(request.getParameter("pwd"));
        adminUsersService.update(u);
        //根据权限ID获取菜单
//        JSONArray res = hasAllForJSON(999 + "");
        JSONArray res = hasAllForJSON(u.getAdminRoles().getId() + "");
        u.setMenu(res);
        log.info("user:" + u);

        return ServerResponse.createBySuccess(u);
    }

    @Autowired
    private AdminRoleMenuService adminRoleMenuService;

    public JSONArray hasAllForJSON(String id) {

        log.info("in to hasAllForJSON");

        List<AdminRoleMenu> mlist = new ArrayList<AdminRoleMenu>();
        mlist = adminRoleMenuService.hasAllByRoleId(id);

        List<AdminMenu> alist = new ArrayList<AdminMenu>();
//        alist=adminMenuService.hasAll();

        for (AdminRoleMenu ar : mlist) {
            // 提防菜单被删了
            if (ar.getMenu() != null) {
                alist.add(ar.getMenu());
            }
        }

        JSONArray res = new JSONArray();
        for (AdminMenu aa : alist) {
            if (aa.getParent_id() == 0) {
                aa = setC(aa, alist);
                res.add(aa);
            }

        }
        return res;

    }

    public AdminMenu setC(AdminMenu aa, List<AdminMenu> alist) {
        aa.setChildrens(new ArrayList<>());
        for (AdminMenu bb : alist) {
            if (bb.getParent_id() == aa.getId()) {
                bb = setC(bb, alist);
                aa.getChildrens().add(bb);
            }

        }

        return aa;
    }

    @CrossOrigin
    @ResponseBody
    @GetMapping("/hasLoginMsg")
    public ServerResponse<?> hasLoginMsg(HttpServletRequest request, HttpSession session) {
        log.info("in to hasLoginMsg" + request.getParameter("token"));
//        AdminUsers au= DataMapUtil.getObject(request.getParameter("token"), AdminUsers.class);
        AdminUsers au = (AdminUsers) session.getAttribute(request.getParameter("token"));
        log.info(au);
        return ServerResponse.createBySuccess(au);
    }


    @CrossOrigin
    @ResponseBody
    @GetMapping("/loginOut")
    public ServerResponse<?> loginOut(HttpSession session) {
        log.info("in to loginOut");
        SecurityUtils.getSubject().logout();
        try {
            session.removeAttribute("loginUser");
        } catch (Exception e) {

        }

        return ServerResponse.createBySuccess(1);
    }
}
